package com.itfreer.gis.map;

import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itfreer.file.FileSegmentInfo;
import com.itfreer.file.service.BucketManageService;
import com.itfreer.file.service.ObjectUploadService;
import com.itfreer.utils.file.FileMeta;
import com.itfreer.utils.file.FilePara;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 文件上传下载服务
 */
@RestController
@RequestMapping("/file/sprite")
@Api("文件上传服务")
public class RestStaticFileService {

	@Autowired(required = false)
	private ObjectUploadService objectUploadService;
	@Reference(lazy = true, check = false)
	private ObjectUploadService dubboObjectUploadService;
	@Autowired
	private FilePara filePara;

	protected ObjectUploadService getObjectUploadService() {
		if (objectUploadService == null) {
			return dubboObjectUploadService;
		} else {
			return objectUploadService;
		}
	}

	@Autowired(required = false)
	private BucketManageService bucketManageService;
	@Reference(lazy = true, check = false)
	private BucketManageService dubboBucketManageService;

	protected BucketManageService getBucketManageService() {
		if (bucketManageService == null) {
			return dubboBucketManageService;
		} else {
			return bucketManageService;
		}
	}

	/**
	 * 文件上传
	 */
	@ApiOperation(value = "文件上传", notes = "")
	@PostMapping(value = "/upload/{key}")
	public LinkedList<FileMeta> upload(@PathVariable("key") final String key, MultipartHttpServletRequest request,
			HttpServletResponse response) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		FileMeta fileMeta = null;
		// 1. build an iterator
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;

		// 创建存储块
		String bucketName = "sprite2";

		// 2. get each file
		while (itr.hasNext()) {
			// 2.1 get next MultipartFile
			mpf = request.getFile(itr.next());

			// 2.2 if files > 10 remove the first from the list
			if (files.size() >= 10) {
				files.pop();
			}

			String fileName = mpf.getOriginalFilename();

			fileMeta = new FileMeta();
			// 只允许上传json和png的文件
			if (fileName.endsWith(".json") || fileName.endsWith(".png")) {
				// 2.3 create new fileMeta
				fileMeta.setName(fileName);
				fileMeta.setSize(mpf.getSize() / 1024);
				fileMeta.setType(mpf.getContentType());
				fileMeta.setCreateTime(new Date());

				getObjectUploadService().createDir(bucketName, key);
				String fileKey = key + "/" + fileName;
				fileMeta.setKey(fileKey);
				fileMeta.setBucketName(bucketName);
				fileMeta.setUrl(filePara.getDownloadUrl(fileMeta));

				try {
					FileSegmentInfo fileSegmentInfo = new FileSegmentInfo();
					fileSegmentInfo.setSegmentContent(mpf.getBytes());
					fileSegmentInfo.setSegmentIndex(0);
					fileSegmentInfo.setSegmentSize(mpf.getBytes().length);
					fileSegmentInfo.setFileLength(mpf.getBytes().length);

					if (getObjectUploadService().uploadFile(bucketName, fileKey, fileSegmentInfo, null)) {
						fileMeta.setStatus("done");
					} else {
						fileMeta.setStatus("error");
						fileMeta.setResponse("上传失败");
					}
				} catch (Exception e) {
					fileMeta.setStatus("error");
					fileMeta.setResponse("上传失败");
				}
			} else {
				fileMeta.setStatus("error");
				fileMeta.setResponse("只能上传.png或.json文件");
			}

			// 2.4 add to files
			files.add(fileMeta);
		}
		return files;
	}
}